#include "login.h"


int littleLogin(const char *usrname,const char *password, MYSQL *mysql){
    char salt[128] = {0};
    char encrypted_password[255] = {0};
    char sql[128];
    sprintf(sql,"select count(*) from usrtable;");

    bzero(sql,sizeof(sql));
    sprintf(sql,"select salt from usrtable where username = '%s';",usrname);

    int qret = mysql_query(mysql,sql);
    printf("%d\n",qret);
    if(qret != 0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result = mysql_store_result(mysql);
    if (mysql_num_rows(result) == 0) {
        printf("No user found with username: %s\n", usrname);
        mysql_free_result(result);
        return -1;
    }
    
    if(mysql_num_rows(result) == 0){
        printf("kong\n");
        return 0;
    }
    MYSQL_ROW row;
    row = mysql_fetch_row(result);
    //获得盐值
    printf("before salt\n");
    sprintf(salt,"%s\t", row[0]);
    printf("salt = %s\n",salt);
    bzero(sql,sizeof(sql));
    sprintf(sql,"select encrypted_password from usrtable where username = '%s';",usrname);
    //printf("%s\n",sql);
    int qret2 = mysql_query(mysql,sql);
    if(qret2 != 0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result2 = mysql_store_result(mysql);
    MYSQL_ROW row2;
    row2 = mysql_fetch_row(result2);
    //获得数据库中的密文密码
    sprintf(encrypted_password,"%s\t", row2[0]);
    //printf("key = %s\n",encrypted_password);
    bzero(sql,sizeof(sql));
    int is_deleted;
    sprintf(sql,"select is_deleted from usrtable where username = '%s';",usrname);
    int qret3 = mysql_query(mysql,sql);
    if(qret3 != 0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result3 = mysql_store_result(mysql);
    MYSQL_ROW row3;
    row3 = mysql_fetch_row(result3);
    is_deleted = atoi(row3[0]);
    printf("is_deleted = %d\n",is_deleted);
    //通过用户输入的密码获得密文密码
    char encrypted_key[255] = {0};
    salt[20] ='\0';
    strncpy(encrypted_key,crypt(password,salt),strlen(crypt(password,salt)));
    //printf("key2 = %s\n",crypt("123","$6$4ZoCxo6jMv4aC9ts$"));
    //printf("encrypted_key = %s\n",encrypted_key);
    if(strncmp(encrypted_key,encrypted_password,strlen(crypt(password,salt))) == 0  && is_deleted == 0){
        printf("登录成功！\n");
        return 0;
    }
    printf("用户名或密码错误！\n");
    return -1;
}
